/**
 * 
 */
package com.et114.modules.products.search;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.queryParser.QueryParser;
import org.compass.core.CompassCallback;
import org.compass.core.CompassException;
import org.compass.core.CompassHighlighter;
import org.compass.core.CompassHits;
import org.compass.core.CompassQueryBuilder;
import org.compass.core.CompassSession;

import com.et114.components.simpletable.DataList;


/**
 * @author guanhw
 * 
 */
public class SearchResultCallback implements CompassCallback {
	protected Log logger = LogFactory.getLog( this.getClass( ) );
	private String key;
	private int pageNum;
	private int pageSize;

	public SearchResultCallback( String key , int pageNum , int pageSize ) {
		this.key = key ; 
		this.pageNum = pageNum ; 
		this.pageSize = pageSize ; 
	}
	
	public Object doInCompass ( CompassSession session ) throws CompassException {
		// TODO Auto-generated method stub
		List < SearchVo > data = new ArrayList < SearchVo > ( );

		
		CompassQueryBuilder queryBuilder = session.queryBuilder ( );
		// session.find ( "searchVo.proTitle:" + key ) ;
		
		CompassHits hits = queryBuilder
				.queryString ( QueryParser.escape ( key ) ).setAnalyzerByAlias (
						"searchVo" ).toQuery ( ).hits ( );
		
		logger.info ( "hits length:" + hits.length ( ) );
		if ( pageNum < 0 )
			pageNum = 1;
		if ( pageSize < 0 )
			pageSize = 1;
		int startIndex = pageSize * ( pageNum - 1 );
		int lastIndex = pageSize * pageNum;


		
	
		if ( lastIndex > ( hits.length ( ) ) )
			lastIndex = hits.length ( ) ; 
		
		
		
		for ( int i = startIndex  ; i < lastIndex  ; i ++ ) {
			SearchVo add = ( SearchVo ) hits.data ( i );
			// 设置高亮显示
			if ( hits.highlighter ( i ).fragment ( "proTitle" ) != null ) 
				add.setProTitle ( hits.highlighter ( i ).fragment ( "proTitle" ) ) ;
			
			if ( hits.highlighter ( i ).fragment ( "proContent" ) != null ) {
				String content = hits.highlighter(i).setTextTokenizer(
						CompassHighlighter.TextTokenizer.AUTO)
						.fragment( "proContent" ); 	
				add.setProContent ( content ) ; 
			}
			
			if ( hits.highlighter ( i ).fragment ( "model" ) != null ) 
				add.setModel ( hits.highlighter ( i ).fragment ( "model" ) ) ; 
			
			if ( hits.highlighter ( i ).fragment ( "brandCn" ) != null ) 
				add.setBrandCn ( hits.highlighter ( i ).fragment ( "brandCn" ) ) ; 
			
			if ( hits.highlighter ( i ).fragment ( "brandEgn" ) != null ) 
				add.setBrandEgn ( hits.highlighter ( i ).fragment ( "brandEgn" ) ) ; 
			
			if ( hits.highlighter ( i ).fragment ( "subj" ) != null ) 
					add.setSubj ( hits.highlighter ( i ).fragment ( "subj" ) ) ; 

		
			data.add ( add );
		}		
		
		DataList dl = new DataList( data , hits.length ( )  , pageSize , pageNum ) ; 
		
		return dl;
	}


	
}